package com.tianji.remark.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.api.dto.remark.LikedTimesDTO;
import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.utils.ObjectUtils;
import com.tianji.common.utils.StringUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.remark.constants.RedisConstants;
import com.tianji.remark.domain.dto.LikeRecordFormDTO;
import com.tianji.remark.domain.po.LikedRecord;
import com.tianji.remark.mapper.LikedRecordMapper;
import com.tianji.remark.service.ILikedRecordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.StringRedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import static com.tianji.common.constants.MqConstants.Exchange.LIKE_RECORD_EXCHANGE;
import static com.tianji.common.constants.MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE;
import static com.tianji.remark.constants.RedisConstants.LIKES_TIMES_KEY_PREFIX;
import static com.tianji.remark.constants.RedisConstants.LIKE_BIZ_KEY_PREFIX;

/**
 * <p>
 * 点赞记录表 服务实现类
 * </p>
 *
 * @author ffk
 * @since 2024-06-28
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class LikedRecordRedisServiceImpl extends ServiceImpl<LikedRecordMapper, LikedRecord> implements ILikedRecordService {

    private  final RabbitMqHelper rabbitMqHelper;
    private final StringRedisTemplate redisTemplate;

    @Override
    public void clickLikes(LikeRecordFormDTO likeRecordFormDTO) {
        //是否是点赞，是否执行成功
        boolean flag= likeRecordFormDTO.getLiked()? likeIt(likeRecordFormDTO) : cancealLikeIt(likeRecordFormDTO);

        //执行新增，删除失败，直接返回
        if(!flag){
            return ;
        }

        //统计点赞次数,根据业务id，获取点赞次数
         Long likeTimes = redisTemplate.opsForSet().size(LIKE_BIZ_KEY_PREFIX + likeRecordFormDTO.getBizId());
        if(likeTimes==null){
            return ;
        }

//        Integer countLikes = this.lambdaQuery()
//                .eq(LikedRecord::getUserId, UserContext.getUser())
//                .eq(LikedRecord::getBizId, likeRecordFormDTO.getBizId())
//                .count();

        //点赞次数存redis
        redisTemplate.opsForZSet().add(LIKES_TIMES_KEY_PREFIX + likeRecordFormDTO.getBizType(),
                likeRecordFormDTO.getBizId().toString(),
                likeTimes);


//        //发送消息去更新
//        //format这里是拼接形成routingkey,前面的常量中有一个占位符，后面根据类型占位，如QA
//        rabbitMqHelper.send(LIKE_RECORD_EXCHANGE,
//                            StringUtils.format(LIKED_TIMES_KEY_TEMPLATE, likeRecordFormDTO.getBizType())
//                            , LikedTimesDTO.of(likeRecordFormDTO.getBizId(),countLikes));
    }


    /**
     * 根据ids查询点赞状态
     * @param bizIds 业务id
     * @return 点过赞的业务id
     */
    @Override
    public Set<Long> queryLikedStatus(List<Long> bizIds) {

        Long userId = UserContext.getUser();
        // 2.查询点赞状态
        // executePipelined方法要求的回调函数必须有返回值
        // 但在这个场景下我们并不关心回调的直接结果，因此返回null
        // 实际的点赞状态会通过objects列表返回给调用者
        //使用redisTemplate执行一组Redis命令，
        // 这些命令通过管道（pipeline）一次性发送到Redis服务器以减少网络往返时间，提高效率
        //这里的循环实际上就是在查询每个业务ID对应的点赞集合里是否包含当前用户，即判断用户是否对每个业务点了赞。
        List<Object> objects = redisTemplate.executePipelined((RedisCallback<Object>) connection -> {
            StringRedisConnection src = (StringRedisConnection) connection;
            for (Long bizId : bizIds) {
                String key = LIKE_BIZ_KEY_PREFIX + bizId;
                src.sIsMember(key, userId.toString());
            }
            return null;
        });
        // 3.返回结果
        return IntStream.range(0, objects.size()) // 创建从0到集合size的流
                .filter(i -> (boolean) objects.get(i)) // 遍历每个元素，保留结果为true的角标i
                .mapToObj(bizIds::get)// 用角标i取bizIds中的对应数据，就是点赞过的id
                .collect(Collectors.toSet());// 收集
    }

    @Override
    public void readLikedTimesAndSendMessage(String bizType, int maxBizSize) {
        Set<ZSetOperations.TypedTuple<String>> typedTuples = redisTemplate.opsForZSet().popMin(LIKES_TIMES_KEY_PREFIX + bizType, maxBizSize);

        while(ObjectUtils.isNotEmpty(typedTuples)){
        List<LikedTimesDTO> message=new ArrayList<>(typedTuples.size());
            for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
                String bizId = typedTuple.getValue();
                Double score = typedTuple.getScore();
                message.add(LikedTimesDTO.of(Long.valueOf(bizId), score.intValue()));
            }

            rabbitMqHelper.send(LIKE_RECORD_EXCHANGE,
                    StringUtils.format(LIKED_TIMES_KEY_TEMPLATE, bizType),
                     message);

            typedTuples=redisTemplate.opsForZSet().popMin(LIKES_TIMES_KEY_PREFIX + bizType, maxBizSize);
        }
    }

    //不喜欢
    private boolean cancealLikeIt(LikeRecordFormDTO likeRecordFormDTO) {
//        boolean result = this.remove(new QueryWrapper<LikedRecord>()
//                .eq("biz_id", likeRecordFormDTO.getBizId())
//                .eq("user_id", UserContext.getUser()));
        String key=LIKE_BIZ_KEY_PREFIX+likeRecordFormDTO.getBizId();
        //删除
         Long result = redisTemplate.opsForSet().remove(key, UserContext.getUser().toString());

        return result!=null && result>0;
    }

    //喜欢
    private boolean likeIt(LikeRecordFormDTO likeRecordFormDTO) {
        String key = LIKE_BIZ_KEY_PREFIX + likeRecordFormDTO.getBizId();
        Long result = redisTemplate.opsForSet().add(key, UserContext.getUser().toString());
        return result != null && result > 0;
    }
}
